﻿using AutoMapper;
using MediatR;
using Sale.Api.Application.Command.Discount;
using Sale.Domain;
using Sale.ErrorCode;
using Sale.Infrastructure.Implement;

namespace Sale.Api.Application.Handler.Discount
{
    public class UpdateDiscountHandler : IRequestHandler<UpdateDiscountCommand, ApiResult<int>>
    {
        private readonly ILogger<UpdateDiscountHandler> logger;
        private readonly DatabaseContext db;
        private readonly IMapper mapper;

        public UpdateDiscountHandler(ILogger<UpdateDiscountHandler> logger,DatabaseContext db,IMapper mapper)
        {
            this.logger = logger;
            this.db = db;
            this.mapper = mapper;
        }
        public async Task<ApiResult<int>> Handle(UpdateDiscountCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var discount = db.SqlSugar.Queryable<ClientPriceModel>().Where(x => x.ClientPriceId == request.ClientPriceId).First();
            if (discount == null)
            {
                result.Msg = "折扣方案不存在";
                result.Code = ApiEnum.Fail;
                return await Task.FromResult(result);
            }
            discount=mapper.Map(request,discount);
            int r=await db.SqlSugar.Updateable<ClientPriceModel>(discount).ExecuteCommandAsync();
            if (r > 0)
            {
                result.Msg = "折扣方案修改成功";
                result.Data = r;
                result.Code = ApiEnum.OK;
                logger.LogInformation(result.Msg);
            }
            else
            {
                result.Msg = "折扣方案修改失败";
                result.Data = r;
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
            }
            return await Task.FromResult(result);
        }
    }
}
